<script lang="ts" setup>
import { ref, onMounted } from "vue"
import { createContactsApi, updateContactsApi, getContactsDetailApi } from "@/api/contacts"
import { type CreateOrUpdateContactsRequestData } from "@/api/contacts/types"
import { type FormInstance, type FormRules, ElMessage, UploadUserFile } from "element-plus"
import { useRouter } from "vue-router"
import { CODE_SUCCESS } from "@/utils/service"
import { getImgApi } from "@/api/common"
import { computed } from "vue"
defineOptions({
  // 命名当前组件
  name: "ContactsOperate"
})
const router = useRouter()
const id: string = router.currentRoute.value.params.id as string
const loading = ref<boolean>(false)

//#region 增
const DEFAULT_FORM_DATA: CreateOrUpdateContactsRequestData = {
  id,
  name: "",
  phone: "",
  post: "",
  address: "",
  photo_url: "",
  email: ""
}
const formRef = ref<FormInstance | null>(null)
const formData = ref<CreateOrUpdateContactsRequestData>(JSON.parse(JSON.stringify(DEFAULT_FORM_DATA)))
const formRules: FormRules<CreateOrUpdateContactsRequestData> = {
  name: [{ required: true, trigger: "blur", message: "请输入姓名" }],
  photo_url: [{ required: true, trigger: "blur", message: "请上传图片" }],
  post: [{ required: true, trigger: "blur", message: "请填写岗位" }],
  phone: [{ required: true, trigger: "blur", message: "请填写手机号" }],
  email: [{ required: true, trigger: "blur", message: "请填写邮箱" }],
  address: [{ required: true, trigger: "blur", message: "请填写地址" }]
}

const handleCreateOrUpdate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    const api = !formData.value.id ? createContactsApi : updateContactsApi
    api(formData.value)
      .then(() => {
        ElMessage.success("操作成功")
        router.push("/contacts")
        resetForm()
        gotoList()
      })
      .finally(() => {
        loading.value = false
      })
  })
}
const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = JSON.parse(JSON.stringify(DEFAULT_FORM_DATA))
}

const gotoList = () => {
  router.push("/contacts")
}

//#region 查
const getContactsDetail = () => {
  if (!id) {
    return
  }
  getContactsDetailApi(id)
    .then(async ({ data }) => {
      formData.value = data
      if (data.photo_url) {
        const { data: fileUrl } = await getImgApi({ path: data.photo_url })
        file.value = fileUrl
      }
    })
    .catch(() => {
      formData.value = DEFAULT_FORM_DATA
    })
}
onMounted(() => {
  getContactsDetail()
})

const dialogImgVisible = ref<boolean>(false)
const file = ref<any>()
const handlePreview = async () => {
  if (file.value) {
    dialogImgVisible.value = true
  } else {
    ElMessage.warning("没有可预览的图片")
  }
}
const handleRemove = () => {
  formData.value.photo_url = ""
}
const handleBeforeUpload = (file: any) => {
  return new Promise((resolve, reject) => {
    const isJPG = file.type === "image/jpeg" || "image/png"
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isJPG) {
      ElMessage.error("上传图片只能是 JPG、JPEG、PNG 格式!")
      reject()
    }
    if (!isLt2M) {
      ElMessage.error("上传图片大小不能超过 2MB!")
      reject()
    }
  })
}
const handleSuccess = async (response: any) => {
  if (response.code === CODE_SUCCESS) {
    formData.value.photo_url = response.data
    const { data } = await getImgApi({ path: response.data })
    file.value = data
  }
}
const fileList = computed<UploadUserFile[]>(() => {
  let list: UploadUserFile[] = []
  if (formData.value.photo_url) {
    list = [
      {
        name: formData.value.photo_url.split("/").at(-1) || "",
        url: file.value
      }
    ]
  }
  return list
})
</script>

<template>
  <div class="app-container">
    <!-- 新增/修改 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>{{ id === undefined ? "新增联系人" : "修改联系人" }}</h3>
        </div>
      </template>
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="name" label="姓名">
          <el-input v-model="formData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="name_en" label="姓名(英文)">
          <el-input v-model="formData.name_en" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="photo_url" label="头像">
          <el-upload
            :file-list="fileList"
            list-type="picture-card"
            class="upload-demo"
            action="/api/uploadImg"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :limit="1"
            :before-update="handleBeforeUpload"
            :on-success="handleSuccess"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">头像图片不能超过 2M.</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="formData.email" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="phone" label="手机号">
          <el-input v-model="formData.phone" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="post" label="岗位">
          <el-input v-model="formData.post" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="post_en" label="岗位(英文)">
          <el-input v-model="formData.post_en" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="address" label="地址">
          <el-input v-model="formData.address" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="gotoList">取消</el-button>
        <el-button type="primary" @click="handleCreateOrUpdate" :loading="loading">确认</el-button>
      </template>
    </el-card>
    <el-dialog v-model="dialogImgVisible" title="图片预览" width="800" align-center>
      <img :src="file" style="width: 700px" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogImgVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
